//
//  ComplainsRecordsVC.m
//  NtoccShipper
//
//  Created by mac on 2019/11/9.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "ComplainsRecordsVC.h"
#import "ComplainsRecordsCell.h"
#import "ComplainsRecordsModel.h"
#import "ComplaintDetailVC.h"
#import "ZTXYiChangChuLiAlControllerViewController.h"

@interface ComplainsRecordsVC ()<UITableViewDelegate,UITableViewDataSource>{
    FlexFrameView *header;
}
@property (nonatomic,strong) ComplainsRecordsCell *complainsRecordsCell;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,strong) UISegmentedControl *segment; //分段控制
@property (nonatomic,copy) NSString *strAbnormalFrom; //投诉来源:0->投诉司机 1->投诉货主
@property (nonatomic,copy) NSString *strQueryOrderCode;
@property (nonatomic,strong) CJTextField *fieldSearch;
@end

@implementation ComplainsRecordsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self setTitleName:CJLString(@"投诉记录")];
    [self setBackLeftButton:@""];
    self.complainsRecordsCell = [[ComplainsRecordsCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self createTopView];
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
        [ws.tableView.mj_header beginRefreshing];
    }];
//    [self loadData];
    [self selectSendGoodsType];
    [self initData];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)selectSendGoodsType{
   
    NSArray *array = [NSArray arrayWithObjects:@"我投诉的",@"投诉我的",nil];
    self.segment = [[UISegmentedControl alloc]initWithItems:array];
    self.segment.frame = CGRectMake((SCREEN_WIDTH-LW(180))/2, LW(5) + kStatusBarHeight, LW(180), LW(25));
    [self.segment addTarget:self action:@selector(changeType:) forControlEvents:UIControlEventValueChanged];
    [self.image addSubview:self.segment];
    //
    if (DeviceSystemVersion.doubleValue > 13) {
        UIColor *tintColor = [UIColor cjMainColor];
        UIImage *tintColorImage = [UIImage imageWithColor:[UIColor cjMainColor]];
        // Must set the background image for normal to something (even clear) else the rest won't work
        [self.segment setBackgroundImage:[UIImage imageWithColor:self.segment.backgroundColor ? self.segment.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [self.segment setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
        [self.segment setBackgroundImage:[UIImage imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        [self.segment setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];
        [self.segment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cjWhiteColor], NSFontAttributeName: [UIFont cjTitleFont14]} forState:UIControlStateSelected];
        [self.segment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cjMainColor], NSFontAttributeName: [UIFont cjTitleFont14]} forState:UIControlStateNormal];
        [self.segment setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        self.segment.layer.borderWidth = 0.5;
        self.segment.layer.borderColor = [tintColor CGColor];
        self.segment.selectedSegmentIndex = 0;
    }else{
        self.segment.tintColor = [UIColor cjMainColor];
    }
    self.segment.selectedSegmentIndex = 0;
}

//不同分段
-(void)changeType:(UISegmentedControl *)sender{
    
    if (sender.selectedSegmentIndex == 0) {
        DLog(@"--=-=-==-");
        self.strAbnormalFrom = @"0";
    }else{
        DLog(@"676767676");
        self.strAbnormalFrom = @"1";
    }
    
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ws.refreshType = @"down";
        ws.page = 1;
        [ws.tableView.mj_header beginRefreshing];
    });
}

- (void)createTopView{
//    //    WS(ws);
//    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
//    header = [[FlexFrameView alloc] initWithFlex:@"ComplainsRecordsView" Frame:rcFrame Owner:self];
//    header.flexibleHeight = YES;
//
//    [header layoutIfNeeded];
//    [self.view addSubview:header];
}

- (void)btnSearchTextAction{
    if ([CJRegular getIsStrEmpty:self.fieldSearch.text]) {
        [CJAlert showStringDismissWithDelay:@"请填写查询内容"];
    }else{
        self.strQueryOrderCode = self.fieldSearch.text;
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
    self.strAbnormalFrom = @"0";
    self.strQueryOrderCode = @"";
}

/// <#Description#>
- (void)loadData {

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/orderDetailAbnormal/list",CJBaseUrl);
    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"abnormalFrom":self.strAbnormalFrom,
                             @"orderDetailCode":IsNilOrNull(self.strCode) ? @"":self.strCode
                            };
//
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

//            DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//            if (list.count > 0) {

            if ([ws.refreshType isEqualToString:@"down"]) {
                [ws.modelArray removeAllObjects];
            }

            NSError * error ;
            NSArray *arr = [ComplainsRecordsModel arrayOfModelsFromDictionaries:list error:&error];
            [ws.modelArray addObjectsFromArray:arr];
  
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];

            if (ws.modelArray.count == total.intValue) {
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }

//            }else{
//                [ws.modelArray removeAllObjects];
//                [ws.tableView.mj_header endRefreshing];
//                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//            }
        [ws.tableView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"ComplainsRecordsCell";
    ComplainsRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ComplainsRecordsCell alloc] initWithFlex:nil reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    ComplainsRecordsModel *model = self.modelArray[indexPath.row];
    [cell setCellInfoWithModel:model withtype:self.strAbnormalFrom];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ComplainsRecordsModel *model = self.modelArray[indexPath.row];
//    ComplaintDetailVC *vc = [[ComplaintDetailVC alloc]init];
    ZTXYiChangChuLiAlControllerViewController *vc = [[ZTXYiChangChuLiAlControllerViewController alloc]init];
    vc.orderCode = model.code;
    vc.abnormalFrom = self.strAbnormalFrom;
    [self pushVc:vc];
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end
